import fs from 'fs-extra'
import path from 'path'

//symlink同步
export const symlinkCommon = async () => {
  const src = path.resolve(__dirname, '../Common')
  const dst = path.resolve(__dirname, '../../../client/assets/Scripts/Common')

  try {
    // 检查目标路径是否存在
    const exists = await fs.pathExists(dst)
    if (exists) {
      // 检查是否是符号链接
      const isSymlink = await fs
        .lstat(dst)
        .then(v => v.isSymbolicLink())
        .catch(() => false)
      if (isSymlink) {
        // 如果是符号链接，检查是否指向正确的源
        const currentTarget = await fs.readlink(dst)
        if (currentTarget === src) {
          console.log('同步成功！符号链接已存在且指向正确')
          return
        }
        // 如果指向错误，删除现有的符号链接
        await fs.unlink(dst)
      } else {
        // 如果存在但不是符号链接，先删除
        await fs.remove(dst)
      }
    }

    // 创建新的符号链接
    await fs.symlink(src, dst)
    console.log('同步成功！已创建新的符号链接')
  } catch (e) {
    console.log('同步失败！', e)
  }
}


export const buffer2ArrayBuffer = (buffer: Buffer) => {
  const arrayBuffer = new ArrayBuffer(buffer.length)
  const dataView = new DataView(arrayBuffer)
  for (let i = 0; i < buffer.length; i++) {
    dataView.setUint8(i, buffer[i])
  }

  return dataView.buffer
}
